import { Button, Form, Input, Modal, Select } from 'antd';
import { Space, Table, Tag } from 'antd';
import React, { useState, useEffect } from 'react';
// @ts-ignore
import { useModel } from 'umi';
import { getLabels, runnerList, saveRunner } from '@/services/project';
import type { ColumnsType } from 'antd/es/table';
// @ts-ignore
const { TextArea } = Input;
import { SettingOutlined } from '@ant-design/icons';
import GridContentLocal from '@/pages/global/gloadding';

const App: React.FC = () => {
  const globalData = useModel('globaldata');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [localUniqueID, setlocalUniqueID] = useState('');
  const [labelsAndRunners, setLabelAndRunners] = useState<
    {
      label: PRO.Label;
      runners: PRO.Runner[];
    }[]
  >([]);
  const [currentModel, setCurrentModel] = useState<PRO.Runner>({
    extension_json: '',
    id: 0,
    ip: '',
    labels: '',
    name: '',
    rpc_port: 0,
    unique_id: '',
    virtual: 0,
    ws_port: 0,
    alive: undefined,
  });

  const [dataList, setDataList] = useState<PRO.PageResponse>({
    list: [],
    page: 0,
    page_size: 0,
    total: 0,
  });

  const showAlive = (record: { alive: boolean }) => {
    if (!record.alive) {
      return (
        <div>
          <Tag color="magenta">节点离线</Tag>
        </div>
      );
    } else {
      return (
        <div>
          <Tag color="green">节点在线</Tag>
        </div>
      );
    }
  };
  const showModal = () => {
    form.resetFields();
    setCurrentModel({
      alive: undefined,
      extension_json: '',
      id: 0,
      ip: '',
      labels: '',
      name: '',
      rpc_port: 0,
      unique_id: '',
      virtual: 0,
      ws_port: 0,
    });
    form.setFieldsValue({
      extension_json: '',
      id: 0,
      ip: '',
      labels: '',
      name: '',
      rpc_port: 0,
      unique_id: '',
      virtual: 0,
      ws_port: 0,
    });
    setIsModalOpen(true);
  };
  const [form] = Form.useForm();

  // @ts-ignore
  const columns: ColumnsType<PRO.Runner> = [
    {
      title: '节点名称',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <a>{text}</a>,
    },
    {
      title: 'IP地址',
      dataIndex: 'ip',
      key: 'ip',
    },
    {
      title: '唯一标识',
      dataIndex: 'unique_id',
      key: 'unique_id',
    },
    {
      title: '节点是否存活',
      dataIndex: 'alive',
      key: 'alive',
      render: (_, record) => <div>{showAlive(record)}</div>,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          {/*<a>Invite {record.name}</a>*/}
          {/*<a>Delete</a>*/}
          {record.id}
          <Button
            type="primary"
            icon={<SettingOutlined />}
            onClick={() => {
              // @ts-ignore
              setIsModalOpen(true);
              form.resetFields();
              setCurrentModel(record);
              form.setFieldsValue(record);
            }}
          >
            编辑配置
          </Button>
        </Space>
      ),
    },
  ];

  const formValidate = async () => {
    return new Promise((resolve, reject) => {
      form
        .validateFields()
        .then((values) => {
          resolve(values);
        })
        .catch((errorInfo) => {
          reject(errorInfo);
        });
    });
  };
  const loadData = async (page = 1, pageSize = 10) => {
    try {
      globalData.show();
      const res = await runnerList({
        page: page,
        page_size: pageSize,
        keyword: '',
      });
      globalData.hidden();
      for (let i in res.list) {
        // @ts-ignore
        if (res.list[i].labels) {
          // @ts-ignore
          res.list[i].labels = JSON.parse(res.list[i].labels);
        } else {
          // @ts-ignore
          res.list[i].labels = [];
        }
      }
      setDataList(res);
      const label = await getLabels();
      setlocalUniqueID(res['unique_id']);
      setLabelAndRunners(label);
    } catch (e) {
      globalData.hidden();
    }
  };
  useEffect(() => {
    loadData();
  }, []);

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const handleOk = async () => {
    try {
      await formValidate();
      form.submit();
    } catch (error) {}
  };

  // const onFinishFailed = (errorInfo: {}) => {
  //   console.log('Failed:', errorInfo);
  // };

  const handleSubmit = async (values: PRO.Runner) => {
    try {
      // @ts-ignore
      values.enable_web_hook = values.enable_web_hook == 1;
      values.labels = JSON.stringify(values.labels);
      // @ts-ignore
      delete values.extension_json;
      // 登录
      await saveRunner(values);
      setIsModalOpen(false);
      loadData();
    } catch (error) {
      console.log(error);
    }
  };

  const onCopy = (certB64: string) => {
    let oInput = document.createElement('input');
    oInput.value = certB64;
    document.body.appendChild(oInput);
    oInput.select(); // 选择对象
    document.execCommand('Copy'); // 执行浏览器复制命令
    oInput.remove();
  };

  // @ts-ignore
  // @ts-ignore
  // @ts-ignore
  return (
    <GridContentLocal>
      <Button type="primary" onClick={showModal}>
        集群配置
      </Button>
      <Table
        columns={columns}
        dataSource={dataList.list}
        pagination={{
          showTotal: () => `共 ${dataList?.total} 条`, // 显示总共有多少条
          total: dataList?.total, // 总共有多少条
          onChange: (page, pageSize) => {
            loadData(page, pageSize);
          }, // 页码变化回调函数
          current: dataList.page, // 当前active的页码
          showSizeChanger: true, // 是否显示页面大小变化选择框
        }}
      />
      ;
      <Modal title="编辑节点" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Form
          form={form}
          name="basic"
          labelCol={{
            span: 6,
          }}
          wrapperCol={{
            span: 16,
          }}
          initialValues={currentModel}
          onFinish={async (values) => {
            await handleSubmit(values as PRO.Runner);
          }}
          // onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label=""
            hidden={true}
            name="id"
            rules={[
              {
                required: true,
                message: '请输入项目名称!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="节点IP地址"
            name="ip"
            rules={[
              {
                required: true,
                message: '请输入节点IP!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="节点名称"
            name="name"
            rules={[
              {
                required: true,
                message: '请输入节点名称!',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="节点唯一标识"
            name="unique_id"
            tooltip={
              '在项目路径下输入[bash run.sh v 或者./static/awesome-devops v],当前节点标识：' +
              localUniqueID
            }
            rules={[
              {
                required: true,
                message: '请输入节点唯一标识',
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="rpc 端口"
            name="rpc_port"
            tooltip="查看docker-compose 配置 对外暴露端口默认5687"
            rules={[
              {
                required: true,
                message: '此端口为rpc端口!',
              },
            ]}
          >
            <Input defaultValue={'5687'} />
          </Form.Item>

          <Form.Item
            label="HTTP服务 端口"
            name="ws_port"
            tooltip="查看docker-compose 配置 对外暴露端口默认8585"
            rules={[
              {
                required: true,
                message: '此端口为http端口!',
              },
            ]}
          >
            <Input defaultValue={'8585'} />
          </Form.Item>

          <Form.Item
            label="标签配置"
            tooltip="设置标签后构建与发布将会带有相同标签的节点运行,此功能用于对集群进行分流"
            name="labels"
            rules={[
              {
                required: false,
                message: '请选择标签!',
              },
            ]}
          >
            <Select
              mode="multiple"
              placeholder="请选择标签"
              defaultValue={[]}
              onChange={() => {}}
              style={{ width: '100%' }}
            >
              {labelsAndRunners.map((item: { label: PRO.Label; runners: PRO.Runner[] }) => {
                // @ts-ignore
                return (
                  // @ts-ignore
                  <Option key={item.label.id} value={item.label.id}>
                    <div title={item.label.description}>标签名:{item.label.label}</div>
                    <div>可用节点数量:{item.runners.length}</div>
                  </Option>
                );
              })}
            </Select>
          </Form.Item>

          <Form.Item
            label="扩展字段"
            name="extension_json"
            tooltip="节点cpu与内存资源"
            rules={[
              {
                required: false,
                message: '',
              },
            ]}
          >
            <div>
              <Space size={[0, 8]} wrap>
                <div>
                  <Tag color="magenta">cpu核心数:{currentModel.extension_json?.cpu}</Tag>
                  <Tag color="magenta">cpu空闲核心:{currentModel.extension_json?.cpu_surplus}</Tag>
                </div>
                <div>
                  <Tag color="blue">内存总量:{currentModel.extension_json?.memory_total}</Tag>
                  <Tag color="blue">内存剩余:{currentModel.extension_json?.surplus_memory}</Tag>
                </div>
              </Space>
            </div>
          </Form.Item>
          <Form.Item label="节点描述" name="description">
            <TextArea rows={4} />
          </Form.Item>
        </Form>
      </Modal>
    </GridContentLocal>
  );
};

export default App;
